package com.atxiao.controller;


//通过线程池优化查询速度


import com.atxiao.common.R;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
public class ThreadController {


    @GetMapping("/getGoods")
    public R getGoods()throws Exception{
        R r = new R();
        long start = System.currentTimeMillis();
        String goodsName = this.getGoodsName();
        String merchantName = this.getMerchantName();
        HashMap<String, Object> map = new HashMap<>();

        map.put("Goodsname",goodsName);
        map.put("merchantName",merchantName);
        long end = System.currentTimeMillis();
        long allTime=end-start;
        System.out.println("一共耗时"+allTime+"毫秒");
        r.setMsg(map);
        return r;
    }



    public String getGoodsName() throws Exception{
        Thread.sleep(3000);
        return "爱疯13";
    }

    public String getMerchantName()throws Exception{
        Thread.sleep(3000);
        return "阿里巴巴";
    }


    @GetMapping("/getGoods2")
    public R getGoods2()throws Exception{
        R r = new R();
        HashMap<String, Object> resMap = new HashMap<>();
        //创建定长的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //查询店铺名称的线程
        long start = System.currentTimeMillis();
        executorService.submit(()->{
            try {
                String merchantName = this.getMerchantName();
                resMap.put("merchantName",merchantName);
                System.out.println("merchant:"+merchantName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        //查询商品名称的线程
            executorService.submit(()->{
                try {
                    String goodsName = this.getGoodsName();
                    resMap.put("goodsName",goodsName);
                    System.out.println("goods："+goodsName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
        r.setCode("200");
        r.setMsg(resMap);

        long end = System.currentTimeMillis();
        long allTime=end-start;
        System.out.println("总耗时："+allTime);

        return r;
    }

}
